<?php
/**
 * Created by PhpStorm.
 * User: lvze
 * Date: 2016/9/1
 * Time: 16:56
 */

namespace App\Services;


class WechatInfo
{
    var $appid = "wx0f8d99209d7c5573";
    var $appsecret = "c317d16ccf6a335e0a67e12128d6be68";

    //构造函数，获取Access Token
    public function __construct($appid = NULL, $appsecret = NULL)
    {
        if($appid){
            $this->appid = $appid;
        }
        if($appsecret){
            $this->appsecret = $appsecret;
        }

        //hardcode
        $this->lasttime = 0;
        $this->access_token = "";

        if (time() > ($this->lasttime + 7200)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            //save to Database or Memcache
            $this->access_token = $result["access_token"];
            $this->lasttime = time();
        }
    }

    public function  send_template_message($open_id,$userName)
    {

        // TODO 发送微信模板消息
        // 消息模板
        $template_data = array( 'touser' => $open_id,
            'template_id'=>"58A0DJL6SlpxO7PxgWZscO-dVSemvrmlCKgDy3YX6nk",
            'data' => array(
                'userName'=> array(
                    'value'=> urlencode($userName),
                    'color'=>"#173177"
                ),
            )
        );

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;

        $json_template = json_encode($template_data);
        $res = $this->https_request($url,urldecode($json_template));

        file_put_contents(storage_path('logs').'/hsms_'.date('Y-m-d').'.log', $res, FILE_APPEND);
        return json_decode($res, true);
    }


    public function  set_menu()
    {

        // TODO 发送微信模板消息
        // 消息模板
        $jsonmenu = '{
      "button":[
      {
            "name":"报价工具",
           "sub_button":[
            {
               "type":"view",
               "name":"供货商报价",
               "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e6c58ef78306f8&redirect_uri=http://cmpt.yooojooo.com/wechat/loginCheck&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
            }]
       },
       {
           "name":"敬请期待",
           "sub_button":[
            {
               "type":"click",
               "name":"敬请期待",
               "key":"敬请期待"
            },
            {
               "type":"click",
               "name":"敬请期待",
               "key":"敬请期待"
            }]
       },
       {
           "name":"敬请期待",
           "sub_button":[
            {
               "type":"click",
               "name":"敬请期待",
               "key":"敬请期待"
            },
            {
               "type":"click",
               "name":"敬请期待",
               "key":"敬请期待"
            }]
       }]
 }';

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
        $res = $this->https_request($url,$jsonmenu);

        file_put_contents(storage_path('logs').'/hsms_'.date('Y-m-d').'.log', $res, FILE_APPEND);
        return json_decode($res, true);
    }

    //https请求（支持GET和POST）
    protected function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    public function https_request_file($url, $data = null)
    {
        $time = time();
        $data = http_build_query($data);
        $opts = [
            'http' => [
                'method'=>"POST",
                'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
                    "Content-length:".strlen($data)."\r\n" .
                    "Cookie: foo=bar\r\n" .
                    "\r\n",
                'content' => $data,
            ]
        ];
        $cxContext = stream_context_create($opts);
        $sFile = file_get_contents($url, false, $cxContext);

        $log_content = date('Y-m-d H:i:s')."\r\n".$data."\r\n".$sFile."\r\n\r\n";
        // log
        file_put_contents(storage_path('logs').'/hsms_'.date('Y-m-d').'.log', $log_content, FILE_APPEND);
        return json_decode($sFile);
    }

}